from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Plot_schema
from controller import Plot_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Plot", response_model=Plot_schema.Plot, tags=["Plot"])
async def create_Plot(Plot: Plot_schema.Plot, db: Session = Depends(get_db)):
    return Plot_controller.create_Plot(db, Plot)


@router.get("/Plot/{ID}", response_model=Plot_schema.Plot, tags=["Plot"])
async def get_Plot(ID: int, db: Session = Depends(get_db)):
    db_Plot = Plot_controller.get_Plot(db, ID)
    if db_Plot is None:
        raise HTTPException(status_code=404, detail="Plot not found")
    return db_Plot


@router.get("/Plot", response_model=List[Plot_schema.Plot], tags=["Plot"])
async def get_all_Plot(db: Session = Depends(get_db)):
    all_db_Plot = Plot_controller.get_all_Plot(db)
    if all_db_Plot is None:
        raise HTTPException(status_code=404, detail="0 Plot found, empty table")
    return all_db_Plot


@router.put("/Plot/{ID}", tags=["Plot"])
async def update_Plot(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Plot = Plot_controller.update_Plot(db, ID, field_name, field_value)
        if db_Plot is None:
            raise HTTPException(status_code=404, detail="Plot not found")
        return db_Plot
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Plot/{ID}", tags=["Plot"])
async def delete_Plot(ID: int, db: Session = Depends(get_db)):
    is_deleted = Plot_controller.delete_Plot(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
